﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Math;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Poisson distribution is a distribution over the integers parameterized by one real number.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Poisson : IDiscreteDistribution
    {
        // The Poisson distribution parameter.
        private readonly double mLambda;

        /// <summary>
        /// Initializes a new instance of the <see cref="Poisson"/> class.
        /// </summary>
        /// <param name="lambda">The mean of the distribution.</param>
        public Poisson(double lambda)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lambda);
            }

            mLambda = lambda;
        }


        /// <summary>
        /// Gets the lambda (mean) value of the distribution.
        /// </summary>
        /// <value>The lambda value.</value>
        public double Lambda
        {
            get { return mLambda; }
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "Poisson(Lambda = " + mLambda + ")";
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get { return mLambda; }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get { return System.Math.Sqrt(mLambda); }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get { return mLambda; }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get { throw new Exception("Not implemented yet."); }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IDiscreteDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public int Mode
        {
            get { return (int) System.Math.Floor(mLambda); }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public int Median
        {
            get { throw new Exception("Not implemented yet."); }
        }

        /// <summary>
        /// Computes the probability of a specific value.
        /// </summary>
        public double Probability(int k)
        {
            return System.Math.Exp(-mLambda + k*System.Math.Log(mLambda) - SpecialFunctions.FactorialLn(k));
        }

        /// <summary>
        /// Samples a Poisson distributed random variable.
        /// </summary>
        public int Sample()
        {
            return DoSample(RandomNumberGenerator, mLambda);
        }

        /// <summary>
        /// Samples an array of Poisson distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public int[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mLambda);
        }

        #endregion

        /// <summary>
        /// Check the parameter of the Poisson distribution.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">If the parameter is non-negative.</exception>
        private static void CheckParameters(double lambda)
        {
            if (lambda < 0.0)
            {
                throw new ArgumentOutOfRangeException("lambda", Resources.ParameterCannotBeNegative);
            }
        }

        /// <summary>
        /// Samples a Poisson distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="lambda">The mean of the Poisson distribution.</param>
        public static int Sample(System.Random rnd, double lambda)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lambda);
            }
            
            return DoSample(rnd, lambda);
        }

        /// <summary>
        /// Samples a Poisson distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="lambda">The mean of the Poisson distribution.</param>
        public static int[] Sample(System.Random rnd, int n, double lambda)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(lambda);
            }
            
            return DoSample(rnd, n, lambda);
        }

        /// <summary>
        /// Use Knuth's method to generate Poisson distributed random variables.
        /// </summary>
        private static int DoSample(System.Random rnd, double lambda)
        {
            double C = System.Math.Exp(-lambda);
            double p = 1.0;
            int k = 0;
            do{
                k = k+1;
                p = p * rnd.NextDouble();
            }
            while(p >= C);

            return k-1;
        }

        /// <summary>
        /// Samples an array of Poisson distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="lambda">The mean of the Poisson distribution.</param>
        private static int[] DoSample(System.Random rnd, int n, double lambda)
        {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, lambda);
            }
            return arr;
        }
    }
}